var jwtDecode = require('jwt-decode');

const tokenKey = 'Authorization'
export default {
    saveUserToken: function(token) {
        window.localStorage.setItem(tokenKey, token);
        //   debugger;
        let userInfo = this.getUserInfo();
        window.localStorage.setItem("user-info", userInfo);
        //window.localStorage.setItem("token-iat", userInfo.iat);
        window.localStorage.setItem("token-exp", userInfo.exp);
    },
    getUserToken: function() {
        return window.localStorage.getItem(tokenKey);
    },
    clearUserToken: function() {
        window.localStorage.removeItem(tokenKey);
    },
    getUserInfo: function() {
        if (this.getUserToken()) {
            let userInfo = jwtDecode(this.getUserToken());
            return userInfo;
        }
        return {};
    },
    saveWorkGroupToken: function(token) {
        window.localStorage.setItem(tokenKey, token);
    },
    getWorkGroupToken: function() {
        return window.localStorage.getItem(tokenKey);
    },
    clearWorkGroupToken: function() {
        return window.localStorage.removeItem(tokenKey);
    },
    getWorkGroupTokenData: function() {
        let decodedToken = jwtDecode(this.getUserToken());
        console.log(decodedToken);
        return decodedToken;
    },
    setUsername: function(username) {
        window.localStorage.setItem('username', username);
    },
    getUsername: function() {
        return localStorage.getItem("username");
        // return this.getWorkGroupTokenData().name;
    },
    setTenantId: function(tenantId) {
        window.localStorage.setItem('tenantId', tenantId);
    },
    getTenantId: function() {
        return localStorage.getItem("tenantId");
        // return this.getWorkGroupTokenData().name;
    },
    getRoleId: function() {
        //debugger;
        if (this.getUserInfo().roleIdList.length <= 0) {
            return -1;
        }
        return this.getUserInfo().roleIdList[0];
    },
    getGroupId: function() {
        if (this.getUserInfo().groupIdList.length <= 0) {
            return -1;
        }
        return this.getUserInfo().groupIdList[0];
    },
    getObjRoleList: function() {
        return this.getUserInfo().objRoleList;
    },
    getMenus: function() {
        return this.getWorkGroupTokenData().menus;
    },
    getPermOps: function() {
        let ret = [];
        let ops = this.getWorkGroupTokenData().permOps;
        console.log(this.getWorkGroupTokenData());
        for (let idx in ops) {
            ret.push(ops[idx]);
        }
        return ret;
    },
    clearSessionData: function() {
        window.localStorage.removeItem('username');
        window.localStorage.removeItem('tenantId');
        window.localStorage.removeItem(tokenKey);
        window.localStorage.removeItem('token-iat');
        window.localStorage.removeItem('token-exp');
    }
}